﻿using System;
using TalksLog.Entities;
using TalksLog.Abstraction.Services;
using TalksLog.Abstraction.Repositories;

namespace TalksLog.Services
{
    public class AccountService: AccountServiceBase
    {
        private AccountRepositoryBase _repository;

        public AccountService(AccountRepositoryBase repository)
        {
            _repository = repository;
        }

        public override bool Register(Account account, out string errorMessage)
        {
            errorMessage = null;

            if (_repository.ExistsSameEmail(account))
            {
                errorMessage = "此电子邮箱已被注册";
                return false;
            }

            if (_repository.ExistsSameName(account))
            {
                errorMessage = "此昵称已被占用";
                return false;
            }

            account.CreateTime = DateTime.Now;
            account.Salt = Tools.Encryptor.GetMd5String(Guid.NewGuid().ToString());
            account.Password = Tools.Encryptor.GetMd5String((account.Password + account.Salt));
            _repository.Add(account);

            return true;
        }

        public override Account Find(string email, string password)
        {
            Account account = _repository.Find(email, password);
            return account;
        }

        public override bool ChangePassword(int id, string password, string newPassword)
        {
            Account account = _repository.Find(id);
            if (account == null)
            {
                return false;
            }
            if (Tools.Encryptor.GetMd5String(password + account.Salt) != account.Password)
            {
                return false;
            }
            _repository.UpdatePassword(id, newPassword);
            return true;
        }

        public override bool ChanageName(int id, string newName, out string errorMessage)
        {
            errorMessage = null;

            if (_repository.ExistsSameName(id, newName))
            {
                errorMessage = "该昵称已被占用";
                return false;
            }

            _repository.UpdateName(id, newName);
            return true;
        }
    }
}
